'use strict'
$(function () {
    query();
    let id = location.search.split('?')[1];
    console.log(id);
    if (id) {
        $.get(`http://localhost:8000/product/${id}`,data=>{
            console.log(data);
            $('[name=id]').val(res.data.id)
                $('[name=name]').val(res.data.name)
                $('[name=abstract]').val(res.data.abstract)
                $('[name=content]').val(res.data.content)
                $('[name=classify]').val(res.data.classify)
                $('[name=author]').val(res.data.author)
            
        })
    }
})
function query() {
    let keyword = $('#keyword').val();
    getList(keyword).then(data => {
        renderFn(data);
    })
}
function renderFn(arr) {
    let row = $('.rowData');
    let tb = $('#tb');
    row.remove();
    arr.forEach(item => {
        let html = `
                <tr class="rowData" key="${item.id}">
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                    <td>${item.abstract}</td>
                    <td>${item.content}</td>
                    <td>${item.classify}</td>
                    <td>${item.author}</td>
                    <td>
                        <input type="button" value="编辑" onclick="update(${item.id})" >
                        <input type="button" value="删除" onclick="del(${item.id})" >
                    </td>
                </tr>
                `
        tb.append(html);
    })
}

function update(id) {
    location.href = `./addOrEdit.html?${id}`;
}

function del(id) {
    let Del = confirm(`请确定要删除id为${id}的项目吗？`);
    if (Del) {
        delById(id).then(data => {
            let id = data.data.id;
            $(`[key=${id}]`).remove();
        })
    }
}

function add(obj) {
    location.href = './addOrEdit.html';
    postProduct(obj).then(data => {
        console.log(data);
    })
}


function save() {
    let obj = {
        id: $('[name=id]').val(),
        name: $('[name=name]').val(),
        abstract: $('[name=abstract]').val(),
        content: $('[name=content]').val(),
        classify: $('[name=classify]').val(),
        author: $('[name=author]').val()
    }

    console.log(obj);

    if (obj.id) {
        putProduct(obj.id, obj).then(res => {
            console.log(res);
            if (res.code === 1000) {
                location.href = './index.html';
            } else {
                alert(code.msg);
            }
        })
    } else {
        postProduct(obj).then(data => {
            if (data.code === 1000) {
                location.href = './index.html';
            } else {
                alert(data.msg)
            }

        })
    }
}
function cancel() {
    location.href = './index.html';
}